package cn.net.cfss.fgbp.auth.service;

import cn.net.cfss.fgbp.api.console.inte.ISysRoleMenuService;
import cn.net.cfss.fgbp.auth.config.ConfigProperty;
import cn.net.cfss.fgbp.auth.common.Constants;
import cn.net.cfss.fgbp.base.util.UuidUtil;
import cn.net.cfss.fgbp.base.vo.UserVo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthService {



    @Autowired
    private ISysRoleMenuService sysRoleMenuService;


    @Autowired
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String buildJWT(Long userId,String userName){
        //生成jwt
        Date now = new Date();
        /*Algorithm algo = Algorithm.HMAC256(ConfigProperty.getIns().secretKey);
        String token = JWT.create()
                .withIssuer(Constants.JWT_ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + ConfigProperty.getIns().jwtTokenExpireTime))
                .withClaim(Constants.PARAMS_USERID, userId)//用户ID
                .withClaim(Constants.PARAMS_USERNAME, userName)//用户名
                .sign(algo);*/
        String token= UuidUtil.getUUID();
        return token;
    }



    public void cacheRoles(List<Long> roles,Long userID)
    {

        Map<Long, List<String>> menuMap= sysRoleMenuService.queryMenuByRoleId(roles);
        if(menuMap==null||menuMap.isEmpty())
        {
            log.error("queryMenuByRoleId返回空,userId={},roles={}",userID,roles);
            return;
        }
        //移除旧的
        redisTemplate.delete(Constants.REDIS_KEY_PRE_USER_ROLES+userID);
        //保存
        redisTemplate.opsForList().rightPushAll(Constants.REDIS_KEY_PRE_USER_ROLES+userID,roles);

        for (Long roleId:menuMap.keySet()) {
            List<String> menus= menuMap.get(roleId);
            if(menus==null||menus.size()==0||menus.get(0)==null)
            {
                log.error("菜单为空,roleId={}",roleId);
                continue;
            }
            menus.removeAll(Collections.singleton(null));
            String menuKey=Constants.REDIS_KEY_PRE_ROLE_MENU+roleId;
            stringRedisTemplate.delete(menuKey);
            stringRedisTemplate.opsForList().rightPushAll(menuKey,menus);
            stringRedisTemplate.expire(menuKey,24,TimeUnit.HOURS);
        }
    }
    public void cacheToken(String token,UserVo user)
    {
        redisTemplate.opsForValue().set(token,user,ConfigProperty.getIns().tokenExpireTime,TimeUnit.MILLISECONDS);
    }
}
